/**
 * 
 */
package com.peking.donations.base.util;

import java.io.File;
import java.util.Properties;
import java.util.UUID;

/**
 * @auther wangyazhou
 * @Date: 2016/3/2 0002
 * @Time: 下午 4:18
 */
public abstract class DownloadFileUtils {
	public static String decodeFileName(String fileName) {
		if (fileName == null || fileName.trim().equals("")) {
			return fileName;
		}
		
		return getCompressedUniqueId() + getFileExtName(fileName);
	}
	public static String getFileExtName(String fileName){
		String extName = "";
		if (fileName.lastIndexOf(".") >= 0) {
			extName = fileName.substring(fileName.lastIndexOf("."));
		}
		return extName;
	}
	public static String getFileNameWithoutExt(String fileName){
		String FileId = fileName;
		if (fileName.lastIndexOf(".") >= 0) {
			FileId = fileName.substring(0,fileName.lastIndexOf("."));
		}
		return FileId;
	}
	/**
	 * 获取压缩后的UUID
	 *
	 * @return
	 */
	public static String getCompressedUniqueId() {
		UUID uuid = UUID.randomUUID();
		byte[] byUuid = new byte[16];
		long least = uuid.getLeastSignificantBits();
		long most = uuid.getMostSignificantBits();
		long2bytes(most, byUuid, 0);
		long2bytes(least, byUuid, 8);
		String compressUUID = "";//Base64.encodeBase64URLSafeString(byUuid);
		return compressUUID;
	}

	private static void long2bytes(long value, byte[] bytes, int offset) {
		for (int i = 7; i > -1; i--) {
			bytes[offset++] = (byte) ((value >> 8 * i) & 0xFF);
		}
	}
	/**
	 * 根据传入的id，生成对应的两级目录，
	 * 从而避免太多目录带来的性能下降的问题。
	 *
	 * （原理：取得uuid的hashcode与0xff按位与操作生成0-255的整数作为一级目录；
	 * 右移8位，也即除以256，与0xff按位与生成0-255的整数作为二级目录）
	 *
	 * @param uniqueId
	 * @return
	 */
//	public static String generateFolderPath(String uniqueId) {
//		int dir1 = uniqueId.hashCode()&0xff;
//		int dir2 = (uniqueId.hashCode()>>8)&0xff;
//
//		return dir1 + File.separator + dir2;
//	}

	/**
	 * 根据传入的根目录和uniqueId，生成对应的目录，原理同上
	 * 
	 * @param root
	 * @param uniqueId
	 * @return
	 */
	public static String generateFolderPath(String root, String uniqueId) {
		int dir1 = uniqueId.hashCode()&0xff;      
		int dir2 = (uniqueId.hashCode()>>8)&0xff;
		
		String path = root + File.separator + dir1 + File.separator + dir2;
		File folder = new File(path);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		
		return path;
	}

	/**
	 *
	 * @param path
	 * @return
	 */
	public static String generateFolderPath(String path) {
		File folder = new File(path);
		if (!folder.exists()) {
			folder.mkdirs();
		}

		return path;
	}

	/**
	 *
	 * @return
	 */
	public static boolean isWindowSys(){
		Properties prop = System.getProperties();

		String os = prop.getProperty("os.name");
		System.out.println(os);

		if(os.startsWith("win") || os.startsWith("Win") ) {
			return true;
		}else{
			return false;
		}
	}



	public static void main(String[] args) {
//		long l = 0xFFFFFFFFFFFFFFF;
		File[] roots = File.listRoots();
		for (int i = 0; i < roots.length; i++) {
			System.out.println(roots[i]);
		}
		System.out.println(Long.MAX_VALUE);
	}
}
